package cn.tedu.mall.seckill.controller;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillCommitVO;
import cn.tedu.mall.seckill.exception.SeckillBlockHandler;
import cn.tedu.mall.seckill.exception.SeckillFallbackHandler;
import cn.tedu.mall.seckill.service.ISeckillService;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/seckill")
@Api(tags = "提交秒杀订单")
public class SeckillController {
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/{randCode}")
    @ApiOperation("随机码校验并提交订单")
    @ApiImplicitParam(value = "随机码",name = "randCode",dataType = "string")
    @PreAuthorize("hasRole('user')")
    @SentinelResource(value = "seckill-order",
            blockHandlerClass = SeckillBlockHandler.class,blockHandler = "blockHandler",
            fallbackClass = SeckillFallbackHandler.class,fallback = "fallbackHandler"
     )
    public JsonResult<SeckillCommitVO> commitSeckillOrder(
            @PathVariable String randCode, SeckillOrderAddDTO seckillOrderAddDTO){
        //获取spuId
        Long spuId = seckillOrderAddDTO.getSpuId();
        //获取对应的key
        String randCodeKey = SeckillCacheUtils.getRandCodeKey(spuId);
        //判断Redis中是否存在该key
        if (redisTemplate.hasKey(randCodeKey)) {
            //获取随机码
           String redisRandCode = redisTemplate.boundValueOps(randCodeKey).get()+"";
           //判断redis中是否有信息的丢失
           if(redisRandCode==null)
               throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统内部问题，请联系客服");
           //判断redisRandCode和randCode是否一致
            if(!redisRandCode.equals(randCode))
                throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"没有指定的商品");
            //以上的条件都符合，执行购买操作
            SeckillCommitVO seckillCommitVO = seckillService.commitSeckill(seckillOrderAddDTO);
            return JsonResult.ok(seckillCommitVO);
        }else{
            //没有这个key，直接抛出异常
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"没有该商品");
        }
    }
}
